package com.core.framework.web.easyweb.dispatcher;

import java.util.Hashtable;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.core.framework.web.easyweb.ActionFactory;
import com.core.framework.web.easyweb.EasyAction;
import com.core.framework.web.easyweb.EasywebStatics;
import com.core.framework.web.easyweb.annotation.MethodType;
import com.core.framework.web.easyweb.context.ServletActionContext;
import com.core.framework.web.easyweb.forward.ActionForward;
import com.util.AppUtils;

public class DispatcherAction implements EasywebStatics 
{
    private    HttpServletRequest  request ;
    private    HttpServletResponse response;
    private Hashtable<String, Class<?>> webActionClassMap ;
    static ActionForward  actionForward;
    static {
    		
    	if(DispatcherAction.actionForward==null)
    	{
    		actionForward = new ActionForward();
    	}
    }

	public DispatcherAction ()
	{
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		webActionClassMap = ActionFactory.getInstance().getWebActionClassMap();
	}
	public void excute () 
	{
		try{
		 String actionMethod = actionForward.getActionMethod(request);
		 String actionPath = actionForward.getActionPath(request);
		 //1.首先判断请求的连接是否在已经加载的WebAction容器里面
		 if(webActionClassMap.containsKey(actionPath))
		 {
			 //2.获取容器里面的Action事件类
			 Class<?> actionObject = webActionClassMap.get(actionPath);
			 EasyAction easy = (EasyAction)AppUtils.autowiredBean(actionObject);
			 easy.init(actionMethod);
			 String[] forwradData  =  easy.Process();
			 if(forwradData[0]!=null)
			 {
				 if(forwradData[1]==null ||forwradData[1].equals(MethodType.FORWARD) )
				 {
					 ActionForward.forward(forwradData[0], request, response);
				 }
				 else if(forwradData[1].equals(MethodType.REDIRECT))
				 {
					 ActionForward.sendRedirect(forwradData[0], response);
				 }
					 
			 }
		 }
		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
}
